package com.jiangyg.mall.gateway.support.feign;

import com.jiangyg.mall.core.utils.Assert;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;

/**
 * 类描述：Feign 客户端拦截器
 *
 * @author jiangyg
 * @version 4.0
 * @date 2022-10-13
 */
public class FeignRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        // 1. 获取请求
        final ServerHttpRequest request = FeignRequestHolder.get();
        Assert.notNull(request);
        // 2. 复制 header 参数
        final HttpHeaders headers = request.getHeaders();
        headers.forEach((k, v) -> template.header(k, v.toArray(new String[v.size()])));
        // 3. 复制 cookie 参数
//        final Map<String, HttpCookie> cookies = request.getCookies().toSingleValueMap();
//        if (!cookies.isEmpty()) {
//            final String cookieString = cookies
//                    .values()
//                    .stream()
//                    .map(cookie -> cookie.getName() + "=" + cookie.getValue())
//                    .collect(Collectors.joining(";"));
//            template.header("Cookie", cookieString);
//        }
    }

}
